import 'package:flutter/foundation.dart';

/// 全局拍照状态管理服务
/// 用于跟踪应用中的拍照操作状态，避免拍照时触发未完成考试检查
class PhotoStateService {
  static final PhotoStateService _instance = PhotoStateService._internal();
  factory PhotoStateService() => _instance;
  PhotoStateService._internal();

  // 拍照状态标记
  bool _isTakingPhoto = false;
  
  // 拍照开始时间
  DateTime? _photoStartTime;
  
  // 拍照超时时间（分钟）
  static const int _photoTimeoutMinutes = 10;

  /// 开始拍照操作
  void startPhotoOperation() {
    _isTakingPhoto = true;
    _photoStartTime = DateTime.now();
    debugPrint('📸 PhotoStateService: 开始拍照操作');
    debugPrint('   开始时间: $_photoStartTime');
  }

  /// 结束拍照操作
  void endPhotoOperation() {
    _isTakingPhoto = false;
    _photoStartTime = null;
    debugPrint('📸 PhotoStateService: 结束拍照操作');
  }

  /// 检查当前是否正在拍照
  bool get isTakingPhoto {
    // 如果没有拍照状态，直接返回false
    if (!_isTakingPhoto || _photoStartTime == null) {
      return false;
    }

    // 检查拍照是否超时（防止状态卡住）
    final now = DateTime.now();
    final duration = now.difference(_photoStartTime!);
    
    if (duration.inMinutes > _photoTimeoutMinutes) {
      debugPrint('📸 PhotoStateService: 拍照操作超时，自动重置状态');
      debugPrint('   开始时间: $_photoStartTime');
      debugPrint('   当前时间: $now');
      debugPrint('   持续时间: ${duration.inMinutes}分钟');
      
      // 超时自动重置
      _isTakingPhoto = false;
      _photoStartTime = null;
      return false;
    }

    return true;
  }

  /// 获取拍照状态信息（用于调试）
  Map<String, dynamic> getPhotoStateInfo() {
    return {
      'isTakingPhoto': _isTakingPhoto,
      'photoStartTime': _photoStartTime?.toIso8601String(),
      'durationMinutes': _photoStartTime != null 
          ? DateTime.now().difference(_photoStartTime!).inMinutes 
          : null,
    };
  }

  /// 强制重置拍照状态（用于异常情况）
  void forceReset() {
    debugPrint('📸 PhotoStateService: 强制重置拍照状态');
    _isTakingPhoto = false;
    _photoStartTime = null;
  }
}
